import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {ComponentClass} from 'react'
import {Image, Text, View} from '@tarojs/components'
import Skeleton from 'taro-skeleton'
import {CityLocation} from '../utils/server.interface'
import {http} from '../utils/http'
import {
  LIMIT_FROM_SELLER_SINCE,
  MOVIE_CINEMAS, MOVIE_CITY,
  MOVIE_MOVIES,
  RESOURCE_URL,
  SHARE_PIC
} from '../constants/api'
import {getHeadTop, GetRequest} from "../utils/tools";
import Cinema from "./cinema/cinema";
import Screen from "./cinema/screen";
import {user} from "../utils/user.service";
import {getMoviePoster} from "../utils/poster.service";
import {platform} from "../utils/platform-settting.service";
import {location} from "../utils/location.service";
import {h5Wx} from "../utils/h5.service";
import GzhAuth from "../components/gzh-auth/gzh-auth"
import './info.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  searchKey: string
  cinemaList: any
  searchBarTop: number
  dateAry: any
  movieInfo: any
  regionId: number
  movieId: number
  check: number
  tabsIndex: number
  imageUrl: string
  shareName: string
  sort: number
  location?: any
  ML?: any
  loading: boolean
  isLogin: boolean
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Minfo {
  props: IProps
}

class Minfo extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    cinemaList: [],
    searchKey: '',
    searchBarTop: 0,
    movieInfo: {},
    dateAry: [],
    regionId: 0,
    movieId: 0,
    check: 0,
    tabsIndex: 0,
    imageUrl: '',
    shareName: '',
    sort: 0,
    loading: true,
    isLogin: false,
  }
  page = 1

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    const dateAry = []
    this.setState({searchBarTop, dateAry})
    let movieId = Taro.getCurrentInstance().router.params.id
    const scene = Taro.getCurrentInstance().router.params.scene as string | undefined;
    let bindSellerId
    if (scene && /^\d+_\d+_\d+$/.test(scene)) {
      platform.scene = 0;
      const paramArr = scene.split('_');
      bindSellerId = paramArr[2];
      movieId = paramArr[0];
    } else {
      bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || Taro.getStorageSync('bindSellerId') || 0;
      if (scene) {
        const paramArr = scene.split('_');
        movieId = paramArr[0];
      }
    }
    user.bindSellerId = bindSellerId
    Taro.setStorage({
      key: 'bindSellerId',
      data: user.bindSellerId,
    })
    if (bindSellerId) {
      Taro.login({
        success: async (res) => {
          if (res.code) {
            const integralForm = {
              sellerId: bindSellerId,
              code: res.code,
              name: '电影票列表'
            }
            const a = await http.post(LIMIT_FROM_SELLER_SINCE, integralForm);
          } else {
            //console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
    const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const ML = Taro.getStorageSync("ML");
    if (location.region_id == 0 || location.region_id == undefined) {
      await this.getLocation(movieId)
      return
    }
    await this.getList(location.region_id, ML, movieId)
    await this.initData(location, ML, movieId)
  }

  shareParams = ''

  async componentDidShow() {
    if (!this.state.loading) {
      const location = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
      const ML = Taro.getStorageSync("ML");
      await this.initData(location, ML, this.state.movieId)
    }
    const isLogin = await user.checkLogin()
    if (isLogin) {
      this.shareParams = await user.getSellerParams()
      this.setState({isLogin})
      const res = await http.postCar(SHARE_PIC, {})
      if (res) {
        this.setState({
          imageUrl: res.sharePic,
          shareName: res.shortName,
        })
      }
    }
  }

  async initData(location, ML, movieId) {
    this.setState({location, ML, movieId})
    const msg = await this.getData(this.page, location.region_id, ML, movieId, this.state.regionId)
    if (msg) {
      this.setState({
        cinemaList: msg.cinemaList, loading: false
      })
    }
  }

  async getData(page, cityId, ML, movieId, regionId? = 0) {
    const {sort} = this.state
    let data = {page, count: 20, cityId, lng: ML.lng, lat: ML.lat, movieId, sort: sort ? 'price_asc' : 'distance_asc'}
    if (regionId) {
      data = {
        page,
        count: 20,
        cityId,
        lng: ML.lng,
        lat: ML.lat,
        movieId,
        sort: sort ? 'price_asc' : 'distance_asc',
        regionId
      }
    }
    const List = await http.MGet(MOVIE_CINEMAS, data)
    if (List && List.length >= 20) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return List
  }

  async getList(cityId, ML, movieId) {
    const data = {type: 1, cityId, lng: ML.lng, lat: ML.lat, movieId}
    const list = await http.MGet(MOVIE_MOVIES, data)
    if (list && list.movieList[0]) {
      this.setState({
        movieInfo: list.movieList[0]
      })
    }
  }

  async getLocation(movieId) {
    try {
      // if(process.env.TARO_ENV==='h5'){
      //     h5Wx.getLocation( async (res)=>{
      //       const city = await location.getLocationNewH5City(res.longitude, res.latitude,'wgs84')
      //       Taro.setStorageSync("ML",{lng:res.longitude,lat:res.latitude})
      //       if(city){
      //         await this.checkCity(city.area_name,{lng:res.longitude,lat:res.latitude},movieId)
      //       }
      //     },'wgs84')
      // }else{
      //   Taro.getLocation({
      //     type:'wgs84',
      //     success: async (res) => {
      //       const city = await location.getLocationCity(res.longitude, res.latitude)
      //       Taro.setStorageSync("ML",{lng:res.longitude,lat:res.latitude})
      //       if(city){
      //         await this.checkCity(city.area_name,{lng:res.longitude,lat:res.latitude},movieId)
      //       }
      //     },
      //     fail: () => {
      //       Taro.showModal({
      //         title: '提示',
      //         content: '小程序需要定位权限, 请打开使用我的地理位置',
      //         success:(res) => {
      //           if(res.confirm) {
      //             Taro.openSetting()
      //           }else if (res.cancel) {
      //             Taro.switchTab({
      //               url:'/pages/index/index'
      //             })
      //           }
      //         }
      //       })
      //     }
      //   })
      // }
      location.getLocation().then(async (res: any) => {
        if (res == null) {
          console.log('不是微信浏览器');
        } else {
          if (process.env.TARO_ENV === 'h5') {
            const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
            Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
            if (city) {
              await this.checkCity(city.area_name, {lng: res.longitude, lat: res.latitude}, movieId)
            }
          } else {
            const city = await location.getLocationCity(res.longitude, res.latitude)
            Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
            if (city) {
              await this.checkCity(city.area_name, {lng: res.longitude, lat: res.latitude}, movieId)
            }
          }
        }
      });

    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的信息',
        success: (res) => {
        }
      })
    }
  }

  async checkCity(str, ML, movieId) {
    const that = this
    const ret = await http.MGet(MOVIE_CITY, {})
    if (ret) {
      let val = {}
      const list = ret
      list.map(item => {
        if (str.indexOf(item.city_name) > -1) {
          val = {region_id: item.city_id, area_name: item.city_name}
        }
      })
      if (val.region_id) {
        Taro.setStorageSync("Mlocation", val)
        await that.getList(val.region_id, ML, movieId)
        await that.initData(val, ML, movieId)
      } else {
        Taro.showToast({
          title: '获取城市失败！请手动定位',
          icon: 'none',
          duration: 2000,
        })
        setTimeout(function () {
          Taro.navigateTo({
            url: "/other/select-city/movie-city"
          })
        }, 2000)
      }
    } else {
      Taro.navigateTo({
        url: "/other/select-city/movie-city"
      })
    }
  }

  GetDateStr(AddDayCount) {
    const dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);
    const num = dd.getDay(dd);
    let week = "";
    switch (num) {
      case 0:
        week = "周日";
        break;
      case 1:
        week = "周一";
        break;
      case 2:
        week = "周二"
        break;
      case 3:
        week = "周三"
        break;
      case 4:
        week = "周四"
        break;
      case 5:
        week = "周五"
        break;
      case 6:
        week = "周六"
        break;
      default:
        break;
    }
    ;
    if (AddDayCount == 0) {
      week = "今天"
    } else if (AddDayCount == 1) {
      week = "明天"
    }

    const m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
    const d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return week + m + "月" + d + "日";
  }

  async cheakDate(index) {

    this.setState({
      tabsIndex: index
    })

  }

  async onOther(e) {
    this.page = 1
    this.setState({
      regionId: e
    })
    const {location, ML, movieId} = this.state
    const msg = await this.getData(this.page, location.region_id, ML, movieId, e)
    if (msg) {
      this.setState({
        cinemaList: msg.cinemaList
      })
    }
  }

  async onCOther(e) {
    const that = this
    const {location, ML, regionId, movieId} = this.state
    this.setState({
      sort: e
    }, async () => {
      const msg = await that.getData(that.page, location.region_id, ML, movieId, regionId)
      if (msg) {
        that.setState({
          cinemaList: msg.cinemaList
        })
      }
    })
  }

  formatTime(timeNum) {
    const date = new Date(timeNum)//一定要记得写这个，不然会报date.getFullYear is not a function
    const year = date.getFullYear()
    const month = this.doble(date.getMonth() + 1)
    const day = this.doble(date.getDate())
    const hour = this.doble(date.getHours())
    const minute = this.doble(date.getMinutes())
    return [year, month, day].join('-') + ' ' + [hour, minute].join(':')
  }

  doble(num) {
    let a = num
    if (num < 10) {
      a = '0' + num
    }
    return a;
  }

  async onGetPoster() {
    Taro.showLoading({title: '获取海报中...'});
    const {movieId, movieInfo} = this.state
    const shareParams = await user.getMovieSellerParams()
    const poster = await getMoviePoster({
      path: 'movie/Minfo',
      scene: movieId + '_' + shareParams,
      pageType: 'detail'
    }, movieInfo.poster)
    Taro.hideLoading();
    if (poster) {
      Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
    } else {
      Taro.showToast({title: '获取海报失败！', icon: 'none'})
    }
  }

  onShareAppMessage() {
    const {movieId, movieInfo} = this.state
    return {
      path: '/movie/Minfo?id=' + movieId + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
      title: movieInfo.name ? movieInfo.name : '想看特价电影，就来购吧！',
      imageUrl: RESOURCE_URL + movieInfo.poster
    };
  }

  render() {
    const {loadMoreStatus, searchBarTop, loading, cinemaList, movieId, check, movieInfo, regionId, isLogin} = this.state
    return (
      <View className='movieInfo'>
        <GzhAuth />
        <View className='info-box'>
          <View className='info-content'>
            {movieInfo.poster &&
            <Image className='info-img' src={RESOURCE_URL + movieInfo.poster} mode='aspectFill'></Image>}
            {movieInfo && movieInfo.name &&
            <View className='info-info'>
              <View className='info-name'>{movieInfo.name}</View>
              <View className='info-score'>评分：
                {movieInfo.grade ? <Text>{movieInfo.grade}</Text>
                  : <Text className='no-score'>暂无评分</Text>}
              </View>
              <View className='info-star'>主演：{movieInfo.cast}</View>
              <View className='info-time'>{movieInfo.publish_area}/{movieInfo.duration}分钟</View>
              <View className='info-time'>{this.formatTime(movieInfo.publish_date)} 上映</View>
            </View>
            }
          </View>
        </View>
        <View className='screenBox CinemaBox2'>
          <Screen key='minfo' id='screen' borderColor='#f1f1f1' onOther={this.onOther.bind(this)}
            onCOther={this.onCOther.bind(this)} check={check} regionId={regionId}
            searchBarTop={searchBarTop + 50}
          ></Screen>
        </View>
        <Skeleton loading={loading} row={4} rowHeight={150}>
          <Cinema data={cinemaList} go={movieId}></Cinema>
        </Skeleton>
      </View>
    )
  }
}

export default Minfo as ComponentClass<PageOwnProps, PageState>
